//
//  YTFPhotoView.swift
//  sinaWeibo
//
//  Created by pro on 16/3/7.
//  Copyright © 2016年 pro. All rights reserved.
//

import UIKit

//设置一些值
let photoViewMargin: CGFloat = 10
let photoItemMargin: CGFloat = 5
let YTFPhotoViewCellReuseID = "YTFPhotoViewCellReuseID"

//定义一个删除图片的协议
protocol YTFCollectionViewCellDelegate: NSObjectProtocol {
    //定义删除指定位置图片的方法
    func didRemovePhotoAtIndex(index: Int)
}

//遵循协议
class YTFPhotoView: UICollectionView ,UICollectionViewDataSource,YTFCollectionViewCellDelegate,UICollectionViewDelegate{
    
    //定义一个闭包属性用来回调
    var closure: (()->())?
    
    //定义一个私有数组来接收选择的图片
    private lazy var images: [UIImage] = [UIImage]()

    //自定义控件三步曲
    //重写构造方法
    let flowLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加控件并设置约束
    private func setupUI(){
        
        backgroundColor = UIColor.yellowColor()
        
        //设数据源置代理
        dataSource = self
        
        delegate = self
        
        //注册cell
        registerClass(YTFCollectionViewCell.self, forCellWithReuseIdentifier: YTFPhotoViewCellReuseID)
        
        //设置item大小
        let cellWH = (kUIScreenWidth - 2 * photoViewMargin - 2 * photoItemMargin)/3
        flowLayout.itemSize = CGSizeMake(cellWH, cellWH)
        flowLayout.minimumInteritemSpacing = photoItemMargin
        flowLayout.minimumInteritemSpacing = photoItemMargin
        
    }
    
    //对外公开一个添加图片的方法
    func addImage(image: UIImage){
        
        images.append(image)
        
        //刷新数据
        reloadData()
    }
    
    
    deinit{
        print("photo视图销毁")
    }

}


//MARK -- 数据源方法
extension YTFPhotoView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return images.count
        if images.count == 0 || images.count == 9 {
            return images.count
        }else{
            return images.count + 1
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YTFPhotoViewCellReuseID, forIndexPath: indexPath) as! YTFCollectionViewCell
        
        cell.backgroundColor = randomColor()
        
        //记录cell的下标
        cell.indexPath = indexPath
        
        //数组越界，需要判读
        if indexPath.item >= images.count {
            //这说明是属于加好位置的cell
            //设置这个cell的图片视图为nil
            cell.iconImage = nil
        }else{
        
            cell.iconImage = images[indexPath.item]
        }
        
        //设置代理
        cell.delegate = self

        
        return cell
        
    }
    
    //点击cell的方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count{//这说明点击的是加号
            
            //需要回到控制器去调用添加图片的方法,这里使用闭包
            closure?()
        
        }
        
    }
    
    //
    
    //实现代理方法
    func didRemovePhotoAtIndex(index: Int) {
        //删除指定图片
        images.removeAtIndex(index)
        //刷新数据
        reloadData()
    }

}


//自定义cell
class YTFCollectionViewCell: UICollectionViewCell {
    
    //设置代理属性
    weak var delegate: YTFCollectionViewCellDelegate?
    
    //设置一个属性来记录图片位置
    var indexPath: NSIndexPath?
    
    //定义一个图片属性来接收穿过来的照片
    var iconImage: UIImage? {
        
        didSet{
            
            //判断这个cell是否有图片 没有就设置为加好，隐藏删除按钮
            if iconImage == nil {
                photoImageView.image = UIImage(named: "compose_pic_add")
                deleteButton.hidden = true
            }else{
                photoImageView.image = iconImage
                deleteButton.hidden = false
            }
            
        }
        
    }
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加控件并设置约束
    private func setupUI(){
        
        //添加子控件
        contentView.addSubview(photoImageView)
        contentView.addSubview(deleteButton)
        
        //设置约束
        //图片,这个约束这样写是使得照片填充了整个collectionview
//        photoImageView.snp_makeConstraints { (make) -> Void in
//            photoImageView.frame = bounds
//        }
        photoImageView.frame = bounds
        
        //删除按钮
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
    }
    
    //删除按钮的点击事件
    @objc private func deleteBtnClick(){
        print("照片删除了")
        //调用代理方法
        if let index = indexPath?.item {
            delegate?.didRemovePhotoAtIndex(index)
        }
    }
    
    
    //懒加载
    //图片视图
    private lazy var photoImageView: UIImageView = UIImageView()
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "compose_card_delete_highlighted"), forState: UIControlState.Highlighted)
        
        //设置大小
        button.sizeToFit()
        
        //设置点击事件
        button.addTarget(self, action: "deleteBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}


